﻿using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace Atmk.WaterMeter.MIS.Web.Middlewares
{
    public class OptionsMiddleware
    {
        private readonly RequestDelegate _next;
        private IHostingEnvironment _environment;

        public OptionsMiddleware(RequestDelegate next, IHostingEnvironment environment)
        {
            _next = next;
            _environment = environment;
        }

        public async Task Invoke(HttpContext context)
        {
            this.BeginInvoke(context);
            await this._next.Invoke(context);
        }

        private async void BeginInvoke(HttpContext context)
        {
            var reqOrigin = context.Request.Headers["Origin"].ToString(); 
            if (reqOrigin == "")
            {
                reqOrigin = context.Request.Headers["Referer"].ToString(); ;
            }

            const string url = "https://water-meter-demo.aixiyou.com";
            if (!reqOrigin.Contains(url)) return;
            context.Response.Headers.Add("Access-Control-Allow-Origin",
                reqOrigin);
            context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
            if (context.Request.Method != "OPTIONS")
            {
                return;
            }
            //context.Response.Headers.Add("Access-Control-Allow-Origin",
            //    reqOrigin);
            context.Response.Headers.Add("Access-Control-Allow-Headers",
                new[] {"Origin, X-Requested-With, Content-Type, Accept"});
            context.Response.Headers.Add("Access-Control-Allow-Methods", new[] {"GET, POST, PUT, DELETE, OPTIONS"});
            //context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] {"true"});
            context.Response.StatusCode = 200;
            await context.Response.WriteAsync("OK");
        }
    }

 

}
